#include "drv_adc.h"
uint16_t adc_data[100];
void drv_adc_init(void)
{
	GPIO_InitTypeDef GPIO_InitStruct ;
	ADC_CommonInitTypeDef ADC_CommonInitStruct ;
	ADC_InitTypeDef ADC_InitStruct ;
	DMA_InitTypeDef DMA_InitStruct ;
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,  ENABLE) ;
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1,  ENABLE) ;

	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AN ;
	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0 ;
	GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL ;
	GPIO_Init( GPIOA, &GPIO_InitStruct) ;

	ADC_CommonInitStruct.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled ; //失能DMA直接访问
	ADC_CommonInitStruct.ADC_Mode = ADC_Mode_Independent ;//独立模式
	ADC_CommonInitStruct.ADC_Prescaler = ADC_Prescaler_Div4 ;//预分频
	ADC_CommonInitStruct.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles ; //延时五个时钟周期
	ADC_CommonInit( &ADC_CommonInitStruct) ;

	ADC_InitStruct.ADC_ContinuousConvMode = ENABLE ;
	ADC_InitStruct.ADC_DataAlign = ADC_DataAlign_Right ;
	ADC_InitStruct.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None ;
	ADC_InitStruct.ADC_NbrOfConversion = 1 ;
	ADC_InitStruct.ADC_Resolution = ADC_Resolution_12b ;
	ADC_Init( ADC1, &ADC_InitStruct) ;

	DMA_InitStruct.DMA_BufferSize = 100 ;//需要传输数据数量
	DMA_InitStruct.DMA_Channel = DMA_Channel_0 ;//通道号
	DMA_InitStruct.DMA_DIR = DMA_DIR_MemoryToMemory ;//内存到内存
	DMA_InitStruct.DMA_FIFOMode = DMA_FIFOMode_Disable ;//不适用FIFO模式
	DMA_InitStruct.DMA_Memory0BaseAddr = (uint32_t)adc_data ;//目标地址
	DMA_InitStruct.DMA_MemoryBurst = DMA_MemoryBurst_Single ;//单次触发
	DMA_InitStruct.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord ;//数据半字（16bit）传输
	DMA_InitStruct.DMA_MemoryInc = DMA_MemoryInc_Enable ;//目标地址自增
	DMA_InitStruct.DMA_Mode = DMA_Mode_Circular ;//循环缓存模式

	DMA_InitStruct.DMA_PeripheralBaseAddr = (uint32_t)&ADC1->DR ;//数据来源地址
	DMA_InitStruct.DMA_PeripheralBurst = DMA_PeripheralBurst_Single ;//单次
	DMA_InitStruct.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord ;//半字
	DMA_InitStruct.DMA_PeripheralInc = DMA_PeripheralInc_Enable ;//来源地址自增
	DMA_InitStruct.DMA_Priority = DMA_Priority_VeryHigh ;//优先级高

	DMA_Init(DMA2_Stream0, &DMA_InitStruct) ;//初始化参数

	ADC_RegularChannelConfig(ADC1, ADC_Channel_0, 1, ADC_SampleTime_480Cycles) ;
	ADC_DMARequestAfterLastTransferCmd( ADC1, ENABLE) ;
	DMA_Cmd(DMA2_Stream0, ENABLE) ;//使能
	ADC_Cmd(ADC1, ENABLE);
	ADC_DMACmd(ADC1, ENABLE);

	ADC_SoftwareStartConv(ADC1);
}

uint16_t drv_adc_res_value(void)
{
	uint32_t sum = 0 ;
	uint8_t i = 0 ;

	for (i = 0 ; i < 100; ++i)
	{
		sum  += adc_data[i] ;
	}
	return (uint16_t)(sum) ;
}
